﻿@*<td>
@if (Model.Drawing != null)
{
    <img src="@Url.Content(String.Format("~/Uploads/{0}", Model.Drawing))" width="100" height="100" id="dynamicImg"/>
}
</td>*@
@model  JewererBasic.PRODUCT
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Update Production Card</h2>
@using (Html.BeginForm("Update", "NewProduct", FormMethod.Post, new { @id = "WebGridForm", enctype = "multipart/form-data" }))
{
    if (Model.Drawing != null)
    {
    <img src="@Url.Content(String.Format("~/Uploads/{0}", Model.Drawing))" width="100" height="100" />
    }
    
    <div id="productArea">
        <fieldset>
            <legend>PRODUCTION CARD</legend>            
            <table>
                <tr>
                    <td align="center">
                        <strong class="myStrong">Item</strong>
                    </td>

                    <td align="center">
                        <strong class="myStrong">Metal Weight</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Total Weight</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Size</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Kind</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Unit</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Type</strong>
                    </td>
                    <td align="center">
                        <strong class="myStrong">Gamma</strong>
                    </td>
                </tr>
                <tr>
                    <td>
                        @Html.TextBoxFor(model => model.Id, new { style = "width:100px;", placeholder = "ITem", id = "PCId", required = "required", @readonly = true })            
                        @Html.ValidationMessage("NameProductionCard")
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.MetalWeight, new { id = "PCMetalWeight", @class = "Number", style = "width:80px;", placeholder = "Metal Weight" })
                        @Html.ValidationMessageFor(model => model.MetalWeight)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.TotalWeight, new { id = "PCTotalWeight", @class = "Number", style = "width:80px; ", placeholder = "Total Weight" })
                        @Html.ValidationMessageFor(model => model.TotalWeight)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.Size, new { required = "required", id = "PCSize", @class = "Number", style = "width:40px;", placeholder = "Size" })
                        @Html.ValidationMessageFor(model => model.Size)
                    </td>
                    <td>
                        @Html.DropDownList("IdKind", null, new { id = "PCKind" })
                        @Html.ValidationMessageFor(model => model.IdKind)
                    </td>
                    <td>
                        @Html.DropDownList("IdUnit", null, new { id = "PCUnit" })
                        @Html.ValidationMessageFor(model => model.IdUnit)
                    </td>
                    <td>
                        @Html.DropDownList("IdType", null, new { id = "PCType" })
                        @Html.ValidationMessageFor(model => model.IdType)
                    </td>
                    <td>
                        @Html.DropDownList("IdGamma", null, new { @id = "PCGamma" })
                        @Html.ValidationMessageFor(model => model.IdGamma)
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.MyFile, new { id = "drawing", type = "file" })
                        @Html.TextBoxFor(m => m.Drawing, new { id = "path", @readonly = true })
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
    
                        // casting
    <input type="button" value="Add Casting" id="addCasting" />
    <input type="button" value="Add Stone" id="addStone" />
    <input type="button" value="Add Component" id="addComponent" />
    <input type="button" value="Add Process" id="addProcess" />
    <fieldset id="myfieldset">
        <legend>CASTINGS</legend>
        <div id="castingArea" />
    </fieldset>
    
                        // stone    
    <fieldset>
        <legend>STONES</legend>
        <div id="stoneArea" />
    </fieldset>
    
                        // component    
    <fieldset>
        <legend>COMPONENTS</legend>
        <div id="componentArea" />
    </fieldset>
    
                        // process    
    <fieldset>
        <legend>PROCESSES</legend>
        <div id="processArea" />
    </fieldset>
    
    <fieldset>
        <legend>Remark</legend>
        @Html.TextAreaFor(m => m.Remark, new { id = "remark", rows = "7", cols = "100" })
    </fieldset>
    <input type="submit" value="SAVE" id="try" />
    @Html.ActionLink("Go to Search Product page", "Index", "Product")
}
@section Scripts {
    <script src="~/Scripts/jQuery.FileUpload/jquery.fileupload.js"></script>
    <script src="~/Scripts/jQuery.FileUpload/jquery.fileupload-ui.js"></script>
    <script src="~/Scripts/jQuery.FileUpload/jquery.iframe-transport.js"></script>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>

    @*get data*@
    <script type="text/javascript">
        $('#try').click(function (e) {
            e.preventDefault();
            var flag = 0;

            // get data product
            var IdProduct = $('#PCId').val();
            var Kind = $('#PCKind').val();
            var Size = $('#PCSize').val();
            var Unit = $('#PCUnit').val();
            var Type = $('#PCType').val();
            var MetalWeight = $('#PCMetalWeight').val();
            var TotalWeight = $('#PCTotalWeight').val();
            var Gamma = $('#PCGamma').val();
            var Remark = $('#remark').val();
            if (!IdProduct || !Kind || !Unit || !Type || !Gamma) {
                alert("Wrong data! check Production Card Information");
                return;
            } else {
                var product = new ProductView(IdProduct, Kind, Size, Unit, Type, MetalWeight, TotalWeight, Gamma, Remark);
                AllPost.productView = product;
            }

            // get data casting
            MyCasting.init();
            $('.pCastingTag').each(function () {
                var Item = $(this).children('.ItemCasting').val();
                var Qty = $(this).children('.QtyCastingNumber').val();
                var Unit = $(this).children('.Unit').val();
                var Type = $(this).children('.Type').val();
                if (!Item || !Qty || !Unit || !Type) {
                    flag = 1;
                }
                else {
                    var qty = parseInt(Qty);
                    if (qty <= 0) {
                        flag = 1;
                    } else {
                        var casting = new CastingView(Item, IdProduct, Unit, Type, Qty);
                        MyCasting.Data.push(casting);
                    }
                }
            });

            // get data stone
            MyStone.init();
            $('.pStoneTag').each(function () {
                var Item = $(this).children('.ItemStone').val();
                var Qty = $(this).children('.QtyStoneNumber').val();
                var Weight = $(this).children('.WeightNumber').val();
                if (!Item || !Qty || !Weight) {
                    flag = 1;
                }
                else {
                    var qty = parseInt(Qty);
                    var weight = parseFloat(Weight);
                    if (qty <= 0 || weight <= 0) {
                        flag = 1;
                    } else {
                        var stone = new StoneView(Item, IdProduct, Qty, Weight);
                        MyStone.Data.push(stone);
                    }
                }
            });

            // get data component
            MyComponent.init();
            $('.pComponentTag').each(function () {
                var Item = $(this).children('.ItemComponent').val();
                var Qty = $(this).children('.QtyComponentNumber').val();
                var Weight = $(this).children('.WeightNumber').val();
                if (!Item || !Qty || !Weight) {
                    flag = 1;
                }
                else {
                    var qty = parseInt(Qty);
                    var weight = parseFloat(Weight);
                    if (qty <= 0 || weight <= 0) {
                        flag = 1;
                    } else {
                        var component = new ComponentView(Item, IdProduct, Qty, Weight);
                        MyComponent.Data.push(component);
                    }
                }
            });

            // get data process
            MyProcess.init();
            $('.pProcessTag').each(function () {
                var NameProcess = $(this).children('.Name').val();
                var Time = $(this).children('.TimeNumber').val();
                if (!NameProcess || !Time) {
                    flag = 1;
                } else {
                    var time = parseInt(Time);
                    if (time < 0) {
                        flag = 1;
                    } else {
                        var process = new ProcessView(NameProcess, IdProduct, Time);
                        MyProcess.Data.push(process);
                    }
                }
            });

            if (MyProcess.Data.length == 0) {
                flag = 1;
                alert("There are no Process!");
                return;
            }

            if (flag == 1) {
                alert("Enter wrong data!");
                return;
            }
            AllPost.DataCasting = MyCasting.Data;
            AllPost.DataStone = MyStone.Data;
            AllPost.DataProcess = MyProcess.Data;
            AllPost.DataComponent = MyComponent.Data;
            AllPost.post();
        });

        // function stone
        function StoneView(Item, IdProduct, Qty, Weight) {
            var self = this;
            self.Item = Item;
            self.Qty = Qty;
            self.Weight = Weight;
            self.IdProduct = IdProduct;
        }
        var MyStone = function () {
            return {

                init: function () {
                    MyStone.Data = new Array();
                },
            }
        }();
        // function component
        function ComponentView(Item, IdProduct, Qty, Weight) {
            var self = this;
            self.Item = Item;
            self.Qty = Qty;
            self.Weight = Weight;
            self.IdProduct = IdProduct;
        }
        var MyComponent = function () {
            return {

                init: function () {
                    MyComponent.Data = new Array();
                },
            }
        }();

        // function process
        function ProcessView(NameProcess, IdProduct, Time) {
            var self = this;
            self.NameProcess = NameProcess;
            self.Time = Time;
            self.IdProduct = IdProduct;
        }
        var MyProcess = function () {
            return {
                init: function () {
                    MyProcess.Data = new Array();
                },
            }
        }();

        // function casting
        function CastingView(Item, IdProduct, Unit, Type, Qty) {
            var self = this;
            self.IdMould = Item;
            self.Unit = Unit;
            self.Type = Type;
            self.Qty = Qty;
            self.IdProduct = IdProduct;
        }
        var MyCasting = function () {
            return {

                init: function () {
                    MyCasting.Data = new Array();
                },
            }
        }();

        // productView
        function ProductView(IdProduct, Kind, Size, Unit, Type, MetalWeight, TotalWeight, Gamma, Remark) {
            var self = this;
            self.Id = IdProduct;
            self.Kind = Kind;
            self.Size = Size;
            self.Unit = Unit;
            self.Type = Type;
            self.MetalWeight = MetalWeight;
            self.TotalWeight = TotalWeight;
            self.Gamma = Gamma;
            self.Remark = Remark;
        }

        // all post
        var AllPost = function () {
            return {
                PostUrl: null,

                post: function () {
                    postData = { castings: AllPost.DataCasting, stones: AllPost.DataStone, components: AllPost.DataComponent, processes: AllPost.DataProcess, productView: AllPost.productView };
                    $.ajax({
                        url: '/NewProduct/AllPostUpdate',
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(postData),
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            if (data.Err)
                                alert(data.Err);
                            else
                                window.location.href = data.RedirectTo;
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert(data.responseText);
                        }
                    });
                }

            }
        }();
    </script>

    @*file upload*@
    <script type="text/javascript">
        $(document).ready(function () {
            initAutoFileUpload();
        });

        function initAutoFileUpload() {
            'use strict';

            $('#drawing').fileupload({
                autoUpload: true,
                url: '/NewProduct/UploadFile',
                dataType: 'json',
                add: function (e, data) {
                    var jqXHR = data.submit()
                        .success(function (data, textStatus, jqXHR) {
                            if (data.isUploaded) {
                            }
                            else {
                            }
                            alert(data.message);
                            $('#path').val("File: " + data.filename);
                        })
                        .error(function (data, textStatus, errorThrown) {
                            if (typeof (data) != 'undefined' || typeof (textStatus) != 'undefined' || typeof (errorThrown) != 'undefined') {
                                alert(textStatus + errorThrown + data);
                            }
                        });
                },
                fail: function (event, data) {
                    if (data.files[0].error) {
                        alert(data.files[0].error);
                    }
                }
            });
        }
    </script>
    
    @*functions*@
    <script type="text/javascript">
        // add casting function
        function addCasting(index, Item, Qty, Unit, Type) {
            $('#castingArea').append('<p class="pCastingTag">' +
                           '<strong class="myStrong">Item</strong><input type="text" class="ItemCasting" id="ItemCastingId' + index + '"  style = "width:150px;" placeholder="Item" required id="ItemCastingId' + index + '">' +
                           //'<input type="text" class="Name" placeholder="Name" required id="NameCastingId' + index + '">' +
                           '<strong class="myStrong">Qty</strong><input type="text" class="QtyCastingNumber" placeholder="Qty"  style = "width:100px;" required id="QtyCasting' + index + '">' +
                           '<strong class="myStrong">Unit</strong><input type="text" class="Unit" id="UnitCasting' + index + '" placeholder="Unit" style = "width:100px;" required>' +
                           '<strong class="myStrong">Type</strong><input type="text" class="Type" id="TypeCasting' + index + '" placeholder="Type" style = "width:100px;" required>' +
                           '<a href="#" id="removeCasting" class="myA">Remove </a> </p>');
            $("#ItemCastingId" + index).val(Item);
            $("#QtyCasting" + index).val(Qty);
            $("#UnitCasting" + index).val(Unit);
            $("#TypeCasting" + index).val(Type);
            var mould = $("#ItemCasting" + index);
            $(mould).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Moulds',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(mould).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            var unit = $("#UnitCasting" + index);
            $(unit).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Units',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(unit).val(ui.item.value);
                    return false;
                },
                minLength: 1
            });

            var type = $("#TypeCasting" + index);
            $(type).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Types',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(type).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            // remove additional elements
            $(document).on("click", "#removeCasting ", function () {
                $(this).parents('p').remove();
                return false;
            });
        }
        // add stone function
        function addStone(index, IdStone, Qty, Weight) {
            $('#stoneArea').append('<p class="pStoneTag">' +
                                '<strong class="myStrong">Item</strong><input type="text" id="ItemStone' + index + '" style = "width:150px;" class="ItemStone" placeholder="Item" required>' +
                                '<strong class="myStrong">Weight</strong><input type="text" id="WeightStone' + index + '" class="WeightNumber" placeholder="Weight" style = "width:100px;" required>' +
                                '<strong class="myStrong">Qty</strong><input type="text" id="QtyStone' + index + '" class="QtyStoneNumber" placeholder="Qty"  style = "width:100px;" required>' +
                                '<a href="#" id="removeStone" class="myA">Remove </a> </p>');
            $("#ItemStone" + index).val(IdStone);
            $("#WeightStone" + index).val(Weight);
            $("#QtyStone" + index).val(Qty);

            var stone = $("#ItemStone" + index);
            $(stone).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Stones',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(stone).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            // remove additional elements
            $(document).on("click", "#removeStone ", function () {
                $(this).parents('p').remove();
                return false;
            });
        }
        // add component functions
        function addComponent(index, IdComponent, Qty, Weight) {
            $('#componentArea').append('<p class="pComponentTag">' +
                                 '<strong class="myStrong">Item</strong><input type="text" class="ItemComponent" style = "width:150px;" id="ItemComponent' + index + '" placeholder="Item" required>' +
                                 '<strong class="myStrong">Weight</strong><input type="text" class="WeightNumber" id="WeightComponent' + index + '" placeholder="Weight" style = "width:100px;" required>' +
                                 '<strong class="myStrong">Qty</strong><input type="text" class="QtyComponentNumber" id="QtyComponent' + index + '"  placeholder="Qty"  style = "width:100px;" required>' +
                                 '<a href="#" id="removeComponent" class="myA">Remove </a> </p>');
            $("#ItemComponent" + index).val(IdComponent);
            $("#WeightComponent" + index).val(Weight);
            $("#QtyComponent" + index).val(Qty);
            var component = $("#ItemComponent" + index);
            $(component).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Components',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(component).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            // remove additional elements
            $(document).on("click", "#removeComponent ", function () {
                $(this).parents('p').remove();
                return false;
            });
        }
        // add component functions
        function addProcess(index, NameProcess, Time) {
            $('#processArea').append('<p class="pProcessTag" >' +
                               '<strong class="myStrong">Process</strong><input type="text" class="Name" id="NameProcess' + index + '" style = "width:150px;" placeholder="Name Process" required>' +
                               '<strong class="myStrong">Time</strong><input type="text" class="TimeNumber" id="Time' + index + '" placeholder="Time" required>' +
                               '<a href="#" id="removeProcess" class="myA">Remove </a> </p>');
            // set values
            $("#NameProcess" + index).val(NameProcess);
            $("#Time" + index).val(Time);

            //set function
            var process = $("#NameProcess" + index);
            $(process).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Processes',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(process).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            // remove additional elements
            $(document).on("click", "#removeProcess ", function () {
                $(this).parents('p').remove();
                return false;
            });
        }
    </script>

    @*Add Casting*@
    <script type="text/javascript">
        var index = 1;
        $('#addCasting').click(function () {
            addCasting(index, "", 1, "PC", "A");
            index += 1;
        });
    </script>

    @*Add Stone*@
    <script type="text/javascript">
        var index = 1;
        $('#addStone').click(function () {
            addStone(index, "", "", "");
            index += 1;
        });
    </script>

    @*Add Component*@
    <script type="text/javascript">
        var index = 1;
        $('#addComponent').click(function () {
            addComponent(index, "", "", "");
            index += 1;
        });
    </script>

    @*Add Process*@
    <script type="text/javascript">
        var index = 1;
        $('#addProcess').click(function () {
            addProcess(index, "", "0");
            index += 1;
        });
    </script>

    @*allow number only textbox with class end with Number*@
    <script type="text/javascript">
        $(document).ready(function () {
            $("div[id$='Area']").on('keydown', 'input[class$=\'Number\']', function (event) {
                if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                (event.keyCode == 65 && event.ctrlKey === true) ||
                (event.keyCode >= 35 && event.keyCode <= 40)
                    ) {
                    return;
                }
                else {
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    }
                    else {
                        var $focused = $(':focus');
                        if ($focused.val().length >= 10) {
                            $focused.keydown(function (event) {
                                event.preventDefault();
                            })
                        }
                    }
                }
            });

        });
    </script>

    @*set data*@
    <script type="text/javascript">
        $(document).ready(function () {
            //$('#but').click(function(){
            $.ajax({
                url: '/NewProduct/GetDataForUpdate',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    if (data.ca) {
                        jQuery.each(data.ca, function (index, item) {
                            addCasting(-index, item.IdMould, item.Qty, item.Unit, item.Type);
                        });
                    }
                    if (data.st) {
                        jQuery.each(data.st, function (index, item) {
                            addStone(-index, item.Item, item.Qty, item.Weight);
                        });
                    }
                    if (data.co) {
                        jQuery.each(data.co, function (index, item) {
                            addComponent(-index, item.Item, item.Qty, item.Weight);
                        });
                    }
                    if (data.pr) {
                        jQuery.each(data.pr, function (index, item) {
                            addProcess(-index, item.NameProcess, item.Time);
                        });
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Loi load data");
                }
            });
        });
    </script>
}